package com.kly.manager;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import com.kly.config.CosClientConfig;
import com.kly.domain.dto.file.UploadPictureResult;
import com.kly.exception.BusinessException;
import com.kly.exception.ErrorCode;
import com.kly.exception.ThrowUtils;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.model.ciModel.persistence.ImageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.time.LocalDate;
import java.util.Arrays;
import java.util.List;

/**
 * @author admin
 * @date 2025/3/3
 */
@Component
@Slf4j
@Deprecated
public class FileManager {

    /**
     * 单张图片最大为 2M
     */
    private static final long ONE_M = 1024 * 1024L;

    /**
     * 文件格式信息
     */
    private static final List<String> IMAGE_FORMATS = Arrays.asList("jpg", "jpeg", "png", "gif", "bmp", "webp");

    @Resource
    private COSClient cosClient;

    @Resource
    private CosClientConfig cosClientConfig;

    @Resource
    private CosManager cosManager;


    // 将本地文件上传到 COS
    public UploadPictureResult uploadFile(MultipartFile multipartFile, String uploadPathPrefix) {
        // 校验图片
        validatePictureInfo(multipartFile);
        // 文件重命名
        String uploadPath = String.format("%s/%s", uploadPathPrefix, renameFile(multipartFile.getOriginalFilename()));
        // 上传文件

        //     获取文件名
        File tempFile = null;
        try {
            //     创建临时文件
            tempFile = File.createTempFile(uploadPath, "");
            multipartFile.transferTo(tempFile);
            PutObjectResult putObjectResult = cosManager.putPictureObject(uploadPath, tempFile);
            ImageInfo imageInfo = putObjectResult.getCiUploadResult().getOriginalInfo().getImageInfo();
            // 求scale
            int height = imageInfo.getHeight();
            int width = imageInfo.getWidth();
            double scale = NumberUtil.round(width * 1.0 / height, 2).doubleValue();
            // 设置图片信息

            UploadPictureResult uploadPictureResult = UploadPictureResult.builder()
                    .url(cosClientConfig.getHost() + "/" + uploadPath)
                    .picSize(multipartFile.getSize())
                    .picName(multipartFile.getOriginalFilename())
                    .picWidth(width)
                    .picHeight(height)
                    .picScale(scale)
                    .picFormat(imageInfo.getFormat())
                    .build();
            return uploadPictureResult;
            //     上传文件到 COS
        } catch (Exception e) {
            log.error("上传文件失败", e);
        } finally {
            if(tempFile != null) {
                tempFile.delete();
            }
        }

        return null;
    }


    // 上传url地址文件到cos
    public UploadPictureResult uploadUrlFile(String fileUrl, String uploadPathPrefix) {
        // 校验图片url
        validateUrlInfo(fileUrl);
        // 文件重命名
        String uploadPath = String.format("%s/%s", uploadPathPrefix, renameFile(FileUtil.mainName(fileUrl)));
        // 上传文件

        //     获取文件名
        File tempFile = null;
        try {
            //     创建临时文件
            tempFile = File.createTempFile(uploadPath, "");
            // 下载url文件
            HttpUtil.downloadFile(fileUrl, tempFile);

            PutObjectResult putObjectResult = cosManager.putPictureObject(uploadPath, tempFile);
            ImageInfo imageInfo = putObjectResult.getCiUploadResult().getOriginalInfo().getImageInfo();
            // 求scale
            int height = imageInfo.getHeight();
            int width = imageInfo.getWidth();
            double scale = NumberUtil.round(width * 1.0 / height, 2).doubleValue();
            // 设置图片信息

            UploadPictureResult uploadPictureResult = UploadPictureResult.builder()
                    .url(cosClientConfig.getHost() + "/" + uploadPath)
                    .picSize(tempFile.length())
                    .picName(FileUtil.mainName(fileUrl))
                    .picWidth(width)
                    .picHeight(height)
                    .picScale(scale)
                    .picFormat(imageInfo.getFormat())
                    .build();
            return uploadPictureResult;
            //     上传文件到 COS
        } catch (Exception e) {
            log.error("上传文件失败", e);
        } finally {
            if(tempFile != null) {
                tempFile.delete();
            }
        }

        return null;
    }


    /**
     * 校验图片信息
     */
    public void validatePictureInfo(MultipartFile multipartFile) {
        // 校验文件大小
        long size = multipartFile.getSize();
        ThrowUtils.throwIf(size > 2 * ONE_M, ErrorCode.PARAMS_ERROR, "文件大小不能超过 2M");
        //     检验文件名称后缀
        String fileName = multipartFile.getOriginalFilename();
        String suffix = FileUtil.getSuffix(fileName);
        ThrowUtils.throwIf(!IMAGE_FORMATS.contains(suffix), ErrorCode.PARAMS_ERROR, "不支持的文件格式");
    }

    /**
     * 校验Url信息
     */
    public void validateUrlInfo(String fileUrl) {
    //     1. 校验url
        ThrowUtils.throwIf(StrUtil.isBlank(fileUrl), ErrorCode.PARAMS_ERROR, "url不能为空");
    //     2. 校验url是否合法
        try {
            new URL(fileUrl);
        } catch (MalformedURLException e) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "url不合法");
        }
        // 校验域名
        ThrowUtils.throwIf(!fileUrl.startsWith("http://") && !fileUrl.startsWith("https://"), ErrorCode.PARAMS_ERROR, "url不合法");
        //     3. 校验文件是否存在
        HttpResponse response = HttpUtil.createRequest(Method.HEAD, fileUrl).execute();
        ThrowUtils.throwIf(!response.isOk(), ErrorCode.PARAMS_ERROR, "url不合法");
        //     4. 校验文件是否是图片
        String header = response.header("Content-Type");
        final List<String> IMAGE_FORMATS = Arrays.asList("image/jpeg", "image/png", "image/gif", "image/jpg");
        ThrowUtils.throwIf(!IMAGE_FORMATS.contains(header), ErrorCode.PARAMS_ERROR, "url不合法");
        //     5, 校验文件大小
        String lengthStr = response.header("Content-Length");
        ThrowUtils.throwIf(StrUtil.isBlank(lengthStr), ErrorCode.PARAMS_ERROR, "url不合法");
        long length = Long.parseLong(lengthStr);
        ThrowUtils.throwIf(length > 2 * ONE_M, ErrorCode.PARAMS_ERROR, "url不合法");
    }

    /**
     * 文件重命名
     */
    private String renameFile(String fileName) {
        // 取后缀
        String suffix = FileUtil.getSuffix(fileName);
        // 生成唯一文件名
        String uuid = RandomUtil.randomString(16);

        return String.format("%s_%s.%s", LocalDate.now(), uuid, suffix);
    }
}
